package Thread_.homework;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * CAS原子类
 * 编写代码, 基于 AtomicInteger 实现多线程自增同一个变量
 */
public class test22 {
    public static void main1(String[] args) {
        int count=0;
        AtomicInteger atomicInteger = new AtomicInteger();
        for(int i=0;i<1000;i++){
            new Thread(()->{
                atomicInteger.getAndAdd(count);
          }).start();
        }
        System.out.println("count= "+ count);
    }

    private  static AtomicInteger count = new AtomicInteger();
    public static void main(String[] args) throws InterruptedException {
//        Callable callable = new Callable(){
//            @Override
//            public Object call() throws Exception {
//                for(int i=0;i<100;i++){
//                    count.incrementAndGet();
//                }
//                return count.get();
//            }
//        };
//        FutureTask futureTask = new FutureTask(callable);
        Thread[] thread=new Thread[10];
        for(int i=0;i<10;i++){
            thread[i] = new Thread(()->{
                for(int j=1;j<=100;j++){
                    count.incrementAndGet();
                }
            });
            thread[i].start();
        }
        for(Thread t:thread){
            t.join();
        }
        System.out.println("count="+ count.get());

    }
}
